<?
include("xml_request.php");
class WebService
{
    var $xml_input;
    var $xml_request;
    var $const;
    function WebService($xml_input_)
    {
       $this->xml_input = $xml_input_;
       $this->const = new WebServiceConstants();
    }
		
    function process()
    {
	$WS_Active = TRUE;
	//$WS_Active = FALSE;
	if ($WS_Active)
		{
		$xml_responce = ""; 

		$doc = new DOMDocument();
		$doc->loadXML($this->xml_input);
		if(!$doc) $this->error("ERROR_XML_ERROR"); 
//echo $this->xml_input;
		$this->xml_request = new XMLrequest($doc);
		if($this->xml_request->error!="") $this->error($this->xml_request->error);
		switch ($this->xml_request->action)
			{
			case $this->const->ACTION_CATEGORY_LIST:
				$xml_responce = $this->category_list();
				break;
			case $this->const->ACTION_CATEGORY_CONTENT:
				$xml_responce = $this->category_content($this->xml_request->cat_id);
				break;
			case $this->const->ACTION_ITEMS_LIST:
				$xml_responce = $this->items_list();
				break;
			case $this->const->ACTION_ITEM_DETAILS:
				$xml_responce = $this->item_details($this->xml_request->item_code);
				break;
			case $this->const->ACTION_ITEM_AVAILABILITY:
				$xml_responce = $this->item_availability($this->xml_request);
				break;
			case $this->const->ACTION_CHECK_RESERVATION:
				$xml_responce = $this->check_reservation();
				break;
			case $this->const->ACTION_PLACE_RESERVATION:
				$xml_responce = $this->place_reservation();
				break;
			case $this->const->ACTION_CANCEL_RESERVATION:
				$xml_responce = $this->cancel_reservation();
				break;
			case $this->const->ACTION_PING:
				$xml_responce = $this->ping();
				break;
			default:
				$this->error("WRONG_ACTION");                                               
			}
		}          
	else $this->error("WEB_SERVICE_UNAVAILABLE");
	
	$this->XMLResponce($xml_responce);
    }

    function category_list()
    {
		$allcategory=new ItemCategoryBO();
                $allcategory->disabled="0";
		$allcategory->deleted="0";
		$allcategory->load(0,0);
		$xml_str  = "<Status>OK</Status>\r\n<Categorys>\r\n";
		 while($allcategory->Next())
			$xml_str .= "<Category>\r\n<Title><![CDATA[".$allcategory->name."]]></Title>\r\n<Id><![CDATA[".$allcategory->id."]]></Id>\r\n</Category>";
			// Add Night tours included two static tour
                        $xml_str .= "<Category>\r\n<Title><![CDATA[Night tours]]></Title>\r\n<Id><![CDATA[999]]></Id>\r\n</Category>";
		
		$xml_str .= "</Categorys>\r\n";
		return $xml_str;                
    }
    
    function category_content($id)
    {
        if ($id[0]=="999") { //check for Night tours
            $xml_str = "<Status>OK</Status>
<Items>
<Item>
<Title><![CDATA[Night Tour + Top of the Rock]]></Title>
<Code><![CDATA[NTTOR]]></Code>
</Item>
<Item>
<Title><![CDATA[Night Tour + Dinner]]></Title>
<Code><![CDATA[NTPHPM]]></Code>
</Item>
</Items>";
        return $xml_str;
        }
        // end of Night tours

        $allitems=new ItemBO();
        $allitems->data = $allitems->ExecuteQuery('
            SELECT `items_category_item_itemID` , `items`.*
            FROM `items_category_item`
            LEFT JOIN `items` ON `items`.`item_id` = `items_category_item`.`items_category_item_itemID`
            WHERE `items`.`item_deleted`=0 and `items`.`item_disabled`=0 and `items_category_item_catID` ='.$id[0]);
        $xml_str  = "<Status>OK</Status>\r\n<Items>\r\n";
        while($allitems->Next())
                $xml_str .= "<Item>\r\n<Title><![CDATA[".$allitems->title."]]></Title>\r\n<Code><![CDATA[".$allitems->code."]]></Code>\r\n</Item>\r\n";

        $xml_str .= "</Items>\r\n";
        return $xml_str;
    }

    function items_list()
    {
        $allitems=new ItemBO();
        $allitems->disabled="0";
        $allitems->deleted="0";
        $allitems->load(0,0);
        $xml_str  = "<Status>OK</Status>\r\n<Items>\r\n";
         while($allitems->Next())
                $xml_str .= "<Item>\r\n<Title><![CDATA[".$allitems->title."]]></Title>\r\n<Code><![CDATA[".$allitems->code."]]></Code>\r\n</Item>\r\n";

        $xml_str .= "</Items>\r\n";
        return $xml_str;
    }

    function item_details($ids)
    {
        $warning="";
        if (count($ids)!=1) $this->error("WRONG_ITEM_ID");
        $detailed_item= new ItemBO();
        $detailed_item->code=$ids[0];
        $detailed_item->disabled="0";
        $detailed_item->deleted="0";
        $detailed_item->Load(0,0);
        $xml_str=$ids;
        if ($detailed_item->getRowsCount()!=1)
            {
            $this->error("WRONG_ITEM_ID");
            }
        else
	    {
            $detailed_item->Next();
            $today   = date("Y-m-d");
            $prices = $detailed_item->calculatePrice($this->xml_request->partner_id,$today,1,1,$this->xml_request->partner_id,0);
            if ($detailed_item->type!=0)
                switch ($detailed_item->type)
                {
                case 2:
                case 4:
                        $detailed_item->type=2;	break;                //Ticket or broadway
                case 3:
                        $detailed_item->type=3;	break;                //meal
                default:
                        $detailed_item->type=$detailed_item->is_tour==0?0:1; //tour or attrations
                        break;
                }
            $xml_str = "<Status>OK</Status>\r\n";
            if (!empty($warning))
                $xml_str .= "<Warning><![CDATA[".$warning."]]></Warning>";
            $xml_str .= "\t<Id><![CDATA[".$detailed_item->id."]]></Id>\r\n";
            $xml_str .= "\t<Title><![CDATA[".$detailed_item->title."]]></Title>\r\n";
            $xml_str .= "\t<Code><![CDATA[".$detailed_item->code."]]></Code>\r\n";
            $xml_str .= "\t<AdultPrice>".$detailed_item->adult_price."</AdultPrice>\r\n";
            $xml_str .= "\t<ChildPrice>".$detailed_item->child_price."</ChildPrice>\r\n";
            $xml_str .= "\t<WebAdultPrice>".$prices->adult_price."</WebAdultPrice>\r\n";
            $xml_str .= "\t<WebChildPrice>".$prices->child_price."</WebChildPrice>\r\n";
            $xml_str .= "\t<NeedDate>".$detailed_item->need_date."</NeedDate>\r\n";
            $xml_str .= "\t<NeedTime>".$detailed_item->need_time."</NeedTime>\r\n";
            $xml_str .= "\t<Type>".$detailed_item->type."</Type>\r\n";
            $xml_str .= "\t<ChildAgeRange><![CDATA[".$detailed_item->child_age_range."]]></ChildAgeRange>\r\n";
            $xml_str .= "\t<OnlyFor>".$detailed_item->only_for."</OnlyFor>\r\n";
            $xml_str .= "\t<IsNew>".$detailed_item->is_new."</IsNew>\r\n";
            $xml_str .= "\t<IsPackage>".$detailed_item->is_package."</IsPackage>\r\n";
            $xml_str .= "\t<IsCertainDays>".$detailed_item->is_certain_days."</IsCertainDays>\r\n";
            $xml_str .= "\t<CutoffValue>".$detailed_item->cutoff_value."</CutoffValue>\r\n";
            if ($detailed_item->tour_length!="")
                    $xml_str .= "<TourLength><![CDATA[".$detailed_item->tour_length."]]></TourLength>\r\n";
            if ($detailed_item->departure_location!="")
                    $xml_str .= "\t<DepartureLocation><![CDATA[".$detailed_item->departure_location."]]></DepartureLocation>\r\n";
            if ($detailed_item->departure_time!="")
                    $xml_str .= "\t<DepartureTime><![CDATA[".$detailed_item->departure_time."]]></DepartureTime>\r\n";
            if ($detailed_item->location!="")
                    $xml_str .= "\t<Location><![CDATA[".$detailed_item->location."]]></Location>\r\n";
            if ($detailed_item->hours_of_operation!="")
                    $xml_str .= "\t<HoursOfOperation><![CDATA[".$detailed_item->hours_of_operation."]]></HoursOfOperation>\r\n";
            if ($detailed_item->average_visit_time!="")
                    $xml_str .= "\t<AverageVisitTime><![CDATA[".$detailed_item->average_visit_time."]]></AverageVisitTime>\r\n";
            if ($detailed_item->description!="")
                    $xml_str .= "\t<Description><![CDATA[".$detailed_item->description."]]></Description>\r\n";
            if ($detailed_item->note!="")
                    $xml_str .= "\t<Note><![CDATA[".$detailed_item->note."]]></Note>\r\n";
            if ($detailed_item->note_level!="")
                    $xml_str .= "\t<NoteLevel>".$detailed_item->note_level."</NoteLevel>\r\n";
            if ($detailed_item->small_image!="")
                    $xml_str .= "\t<Image><![CDATA[".HTTP_SERVER."/item_img/".$detailed_item->small_image."]]></Image>\r\n";
            if ($detailed_item->image1!="")
                    $xml_str .= "\t<Image1><![CDATA[".HTTP_SERVER."/item_img/".$detailed_item->image1."]]></Image1>\r\n";
            if ($detailed_item->image2!="")
                    $xml_str .= "\t<Image2><![CDATA[".HTTP_SERVER."/item_img/".$detailed_item->image2."]]></Image2>\r\n";
            if ($detailed_item->image3!="")
                    $xml_str .= "\t<Image3><![CDATA[".HTTP_SERVER."/item_img/".$detailed_item->image3."]]></Image3>\r\n";
            
            return $xml_str;
            }
    }

    function item_availability($xml_request)
    {
	$user_id     = 0;
	$error = FALSE;
	$warning="";
	$tour_date = $xml_request->date[0]; //date format MM.DD.YYYY
	$tour_time = $xml_request->time[0];
	$month = substr ($tour_date,0,2);
	$day   = substr ($tour_date,3,2);
	$year  = substr ($tour_date,6,4);

	$estimated_date = $year."-".$month."-".$day;
	
	$item_code = $xml_request->item_code[0];
	$alert_msg = "";
	$item = new ItemBO();
	$item->code=$item_code;
	$item->disabled="0";
	$item->deleted="0";
	$item->Load(0,1);
	
	$affID = $xml_request->partner_id;
	
	$affiliate = new AffiliateBO();
	$is_affiliate = TRUE;  
	$affiliate->id = $affID;
	$affiliate->confirmed = "1";
	$affiliate->blocked   = "0";
	$affiliate->Load(0,1);
	$affiliate->Next();
	
	if($item->Next())
	{
		if (($item->need_date=="1")&&($tour_date=="")) {
			$estimated_date =date("Y-m-d");
			$warning="You did not enter a date. Items price calculated on today";
			}
		if (($item->need_time=="1")&&($tour_time=="")) {
			$estimated_time =date("H:i");
			}
		$item_blackout = new ItemBlackoutBO();
		if($item_blackout->isBlackout($item->id,$estimated_date))
		{
			$error = TRUE;
			$error_message = "Sorry. The item you are trying to book is not available on the day you specified. 
			Please check the day you are trying to book and try again.";
		}
		else
		{
		$item_discount   = new SiteDiscountBO();
		//$discount_string = $item_discount->returnDiscount($item->id,$estimated_date,$is_affiliate,$user_id, $affID);  
		$discount_string = $item_discount->returnDiscount($item->id,$estimated_date,$is_affiliate,$user_id);

		$adult_price = $item->adult_price;
		$child_price = $item->child_price;       	

		if($item->addprice_exist==1)
		{
			$current_day_of_week = date("l", strtotime($estimated_date));       	//0 - sunday, 1- monday ...
	   		$day= "price_".strtolower($current_day_of_week);
			$field_value = $item->{$day};	// Better  swith case
			
			if($field_value==1)
			{
			   $adult_price = $item->addprice_adult;
			   $child_price = $item->addprice_child;       			    	
			}else
			{
				$prices = DailyPricesBO::returnPrice($estimated_date,$item,$xml_request->partner_id);     
				$adult_price = $prices[0];
				$child_price = $prices[1];       		
			}
		  }
		   
		  $affiliate_discount_adult_amount = 0;
		  $affiliate_discount_child_amount = 0;
		  
			if($affiliate->discountAmount>0 && $item->provider==1)
			{
				if ($affiliate->discountType == 0) 
				{
					 $affiliate_discount_adult_amount = ($adult_price/100) * $affiliate->discountAmount;
					 $affiliate_discount_child_amount = ($child_price/100) * $affiliate->discountAmount;
				}else if($affiliate->discountType == 1)
				{
					 $affiliate_discount_adult_amount = $affiliate->discountAmount;
					 $affiliate_discount_child_amount = $affiliate->discountAmount;                    
				}
			}
		  
			if ($affiliate->override_specials == 1)  //overrride specials
			{
				$discount_string = "";
			}
		   
		  if(strlen($discount_string)>0)
		  {
			 //$adult_price_discounted = $item_discount->returnPrice($item->id, $adult_price, $estimated_date, $is_affiliate, $user_id,$affID);
			 //$child_price_discounted = $item_discount->returnPrice($item->id, $child_price, $estimated_date, $is_affiliate, $user_id,$affID);

			 $adult_price_discounted = $item_discount->returnPrice($item->id, $adult_price, $estimated_date, $is_affiliate, $user_id);
			 $child_price_discounted = $item_discount->returnPrice($item->id, $child_price, $estimated_date, $is_affiliate, $user_id);
			 
			 $discount_adult_amount = $adult_price - $adult_price_discounted;
			 $discount_child_amount = $child_price - $child_price_discounted;
			 
			 if($item->provider==1)
			 {
				 if($affiliate_discount_adult_amount > $discount_adult_amount) 
				 {
					 $adult_price = round ($adult_price - $affiliate_discount_adult_amount,2);
					 $child_price = round ($child_price - $affiliate_discount_child_amount,2);
				 }else
				 {
					 $adult_price = $adult_price_discounted;
					 $child_price = $child_price_discounted;               
				 }
			 }else
			 {
		   //    $adult_price = $adult_price_discounted;
		   //    $child_price = $child_price_discounted;               
			 }
		  }
		  else
		  {
			  if($is_affiliate && $affiliate_discount_adult_amount>0 && $item->provider==1)
			  {
				 $adult_price = round ($adult_price - $affiliate_discount_adult_amount,2);
				 $child_price = round ($child_price - $affiliate_discount_child_amount,2);
			  }
		  }
		}	

		if ($error) 
		{
		$xml_str = "\t<Status>ERROR</Status>\r\n ";
		$xml_str .= "\t<Error><![CDATA[".$error_message."]]></Error>\r\n ";
		}
		else
		{
		$xml_str  = "<Status>OK</Status>\r\n";
		if ($warning!="") $xml_str .= "\t<Warning><![CDATA[".$warning."]]></Warning>\r\n";
		$xml_str .= "\t<AdultPrice><![CDATA[".$adult_price."]]></AdultPrice>\r\n ";
		$xml_str .= "\t<ChildPrice><![CDATA[".$child_price."]]></ChildPrice>\r\n ";
		}
	}
	else $this->error("WRONG_ITEM_ID");
      	
    return $xml_str;    
    }

    function check_reservation()
    {
       //TODO: place res
       return "";                
    }

    function place_reservation()
    {
       //TODO: place res
       return "";                
    }

    function cancel_reservation()
    {
       //TODO: send message to admin cancel res   
       return "";      
    }    

    function ping()
    {
        $xml_str  = "<Status>OK</Status>\r\n";
        return $xml_str;
    }

    function error($error_msg)
    {
        $xml_str  = "\t<Status>ERROR</Status>\r\n";
        $xml_str .= "\t<ErrorCode>".$this->const->ERRORS[$error_msg]."</ErrorCode>\r\n";
        $xml_str .= "\t<ErrorMessage><![CDATA[".$error_msg."]]></ErrorMessage>\r\n";
        $this->XMLResponce($xml_str);
        exit(0);
    }

    function XMLResponce($xml_str)
    {
        $responce = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n";
        $responce .= "<XMLResponce>\r\n".$xml_str."</XMLResponce>";
        echo $responce;
    }    
}
?>